package steed.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateEvent;
import steed.netty.module.BaseMsg;
import steed.netty.module.LoginMsg;
import steed.util.base.BaseUtil;

public class ChannelInboundHandler extends SimpleChannelInboundHandler<BaseMsg>{

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
		
	}

	@Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		BaseUtil.getLogger().warn("channel({})断线!",ctx.channel().id().toString());
        NettyChannelMap.remove((SocketChannel)ctx.channel());
        ctx.close();
        super.channelInactive(ctx);
    }
    
    @Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		LoginMsg loginMsg = new LoginMsg();
		ctx.writeAndFlush(loginMsg);
		super.channelActive(ctx);
	}
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
          ctx.fireChannelRead(msg);
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case READER_IDLE:
                    handleReaderIdle(ctx);
                    break;
                case WRITER_IDLE:
                    handleWriterIdle(ctx);
                    break;
                case ALL_IDLE:
                    handleAllIdle(ctx);
                    break;
                default:
                    break;
            }
        }
        super.userEventTriggered(ctx, evt);
    }
    
    protected void handleReaderIdle(ChannelHandlerContext ctx) {
        BaseUtil.getLogger().warn("channel({})读超时",ctx.channel().id().toString());
        ctx.close();
    }

    protected void handleWriterIdle(ChannelHandlerContext ctx) {
    	BaseUtil.getLogger().warn("channel({})写超时",ctx.channel().id().toString());
    }

    protected void handleAllIdle(ChannelHandlerContext ctx) throws Exception {
    	BaseUtil.getLogger().warn("channel({})读写超时,判断为断线!",ctx.channel().id().toString());
//    	channelInactive(ctx);
    	ctx.close();
    }

}
